<template>
  <su-popup
    :show="show"
    @close="onCancel"
    round="30"
  >
    <view
      class="header-title"
      v-if="state.step==1"
    >

      <view class="flex-box">
        微信商户号:{{state.subMchId||'-'}}
        <view
          class="copy-style"
          @click="copySubMchId"
        >复制</view>
      </view>
      <view
        class="right-box"
        @click="viewSteps"
      >
        查看操作步骤
        <div class="img-box">
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250509/d76b92aba2b55f434a3c6a42df337438.png"
            mode="scaleToFill"
          />
        </div>
      </view>
    </view>
    <view :class="['whole', 'bg-white',state.step!==1?'margin-bottom-style':'']">

      <view class="flex top-step">
        <view class="circle">
          1
          <view class="dec">收单协议签约</view>
        </view>
        <view
          class="line"
          style="transform: translateX(60rpx);"
        ></view>
        <view
          class="circle"
          :class="{'noact':state.step<1}"
        >
          2
          <view class="dec">微信授权</view>
        </view>
        <view
          class="line"
          style="transform: translateX(235rpx);"
        ></view>
        <view
          class="circle"
          :class="{'noact':state.step<2}"
        >
          3
          <view class="dec">分账协议</view>
        </view>
      </view>
      <!-- <image
			@tap="saveImg"
			  class="img-code"
			  :src="sheep.$url.cdn(state.sign_img)"
			  mode="widthFix"
			/> -->
      <view class="tip  ss-m-b-10">{{state.tipTxt}}</view>

      <image
        v-if="state.applyStatus!='APPLYMENT_STATE_PASSED'&&state.applyStatus!='APPLYMENT_STATE_FREEZED'"
        @tap="saveImg"
        class="img-code-style"
        :src="state.sign_img"
        mode="widthFix"
      />
      <image
        v-else
        @tap="saveImg"
        class="img-code"
        :src="state.sign_img"
        mode="widthFix"
      />
      <view class="tip">1.点击图片保存图片</view>
      <view class="tip">2.使用微信"扫一扫"扫码</view>
      <view
        class="flex"
        style="margin-top:40rpx"
      >
        <button
          class="ss-reset-button btn-back"
          @tap="onCancel"
        >返回</button>
        <button
          class="ss-reset-button btn-next"
          @tap="nextStep"
        >{{state.step!==2?'下一步':'完成'}}</button>
      </view>
    </view>
  </su-popup>
  <guidelinesPopup
    ref="guidelinesPopupRef"
    :applyStatus="state.applyStatus"
  ></guidelinesPopup>
</template>

<script setup>
import throttle from '@/sheep/helper/throttle.js';
import {
  computed,
  reactive,
  onMounted,
  inject,
  ref,
  watch
} from 'vue';
import {
  onLoad
} from '@dcloudio/uni-app';
	import commissionAPI from "@/ygb/api/commission"
import {
  isEmpty
} from 'lodash';
import sheep from '@/sheep';
import guidelinesPopup from "./guidelinesPopup.vue";
const emits = defineEmits(['cancel', 'end']);
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  jjId: {
    type: [String, Number],
    default: '',
  },
  merchantNo: {
    type: [String, Number],
    default: '',
  }

});


const state = reactive({
  step: 0,
  sign_img: '',
  // sign_img:'/static/icon/surprise_sign.png',
  stepInfo1: {},
  stepInfo2: {},
  info: {},
  subMchId: '',
  applyStatus: '',
  image: ''
});
const guidelinesPopupRef = ref(null)


const saveImg = (url) => {
  console.log('state.sign_img', state.sign_img)
  if (['WechatOfficialAccount', 'H5'].includes(sheep.$platform.name)) {
    sheep.$helper.toast('请长按图片保存');
    return;
  }
  uni.downloadFile({
    url: state.sign_img,
    success: (sres) => {
      console.log(sres);
      uni.saveImageToPhotosAlbum({
        filePath: sres.tempFilePath,
        success: (res) => {
          sheep.$helper.toast('保存成功');
        },
        fail: (err) => {
          sheep.$helper.toast('保存失败');
          console.log('图片保存失败:', err);
        },
      });
    }

  }).onProgressUpdate((res) => {
    uni.showLoading({
      title: '正在保存...'
    })
    if (res.progress == 100) {
      uni.hideLoading()
    }
  })


};

async function nextStep () {
  var oldStep = state.step
  await getCheckInDet()
  if (state.step == oldStep) {
    uni.showToast({
      title: '您尚未完成该步骤',
      duration: 2000,
      icon: 'none'
    })
  }
}

function showModal (msg) {
  uni.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        console.log('用户点击确定');
      }
    }
  });
}

const getCheckInDet = async () => {
  const { error, data } = await commissionAPI.merchant.applyDetailTest(props.jjId, { type: 2 });
  if (error === 0) {
    if (data !== null) {
      state.info = data;
      if (data.agreement === 0) {//未签约--1
        state.step = 0
        await surprise_sign()
      } else {


        state.step = 1//签约完成--1
        if (data.real_name === 0) {//未实名完成--2
          surprise_real()
        } else {


          state.step = 2
          if (data.elec === 0) {//分账未完成----3
            await surprise_elec()
          } else {//两个签约都完成----关闭弹窗
            uni.showToast({
              title: '您已完成扫码签约',
              duration: 1500
            })
            setTimeout(async () => {
              await onCancel()
              emits('end')
            }, 1500)
          }

        }
      }
    }
    console.log('++++++++++++++++', state.step)
  }
};
// 查询签约---step1
async function surprise_sign () {
  const res = await commissionAPI.merchant.surprise_sign(props.jjId)
  if (res.error === 0) {
    state.stepInfo1 = res.data
    //  查询接口获取二维码
    // const ress = await commissionAPI.merchant.surprise_code({url:res.data.contractSignUrl})
    // console.log('查询接口获取二维码',ress)
    let QRcodeTool = 'https://pageandy.liuliangbenben.top/qrcode/build?text='
    let url = QRcodeTool + encodeURIComponent(res.data.contractSignUrl)
    state.sign_img = url
    state.tipTxt = res.msg
  } else {
    uni.showModal({
      title: '提示',
      content: res.msg,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          onCancel()
        }
      }
    });
    // uni.showToast({
    // 	title:res.msg,
    // 	icon:'none',
    // 	duration:3000
    // })
    // setTimeout(()=>{
    // 	onCancel()
    // },3000)
  }
}

// 查询签约---step2
async function surprise_real () {
  const res = await commissionAPI.merchant.surprise_real(props.jjId)
  if (res.error === 0) {
    state.stepInfo2 = res.data
    state.sign_img = state.stepInfo2.qrcodeData
    state.tipTxt = res.msg
    state.applyStatus = res.data.applyStatus
    state.image = res.data.flow_chart
  } else {
    showModal(res.msg)
    // setTimeout(()=>{
    // 	onCancel()
    // },3000)
  }
}

// 查询分账---step3
async function surprise_elec () {
  const res = await commissionAPI.merchant.surprise_elec(props.jjId)
  if (res.error === 0) {
    let QRcodeTool = 'https://pageandy.liuliangbenben.top/qrcode/build?text='
    let url = QRcodeTool + encodeURIComponent(res.data.contractUrl)
    console.log('url++++++++++++', url)
    state.sign_img = url
    state.tipTxt = res.msg
  } else {
    showModal(res.msg)
    // setTimeout(()=>{
    // 	onCancel()
    // },3000)
  }
}
const copySubMchId = () => {
  sheep.$helper.copyText(state.subMchId);
}
const onCancel = () => {
  emits('cancel');
};
const towebview = () => {
  onCancel()
  uni.navigateTo({
    url: '/pages/commission/merchant/webview?url=' + state.stepInfo1.contractSignUrl
  });
};

onMounted(async () => {
  await getCheckInDet()
  await getNum()
})
const getNum = async () => {
  const { error, data } = await commissionAPI.merchant.realNameSubmchQuery(props.merchantNo);
  if (error == 0) {
    state.subMchId = data[0].subMchId
  }
}
const viewSteps = async () => {
  // const { error, data } = await commissionAPI.merchant.getFlowChart();
  // console.log(data);
  // if (error == 0) {
  // freezed 冻结 passed 通过 rejected 驳回
  // const { freezed, passed, rejected } = data
  guidelinesPopupRef.value.open(state.image)
  // }
}
</script>

<style lang="scss" scoped>
.header-title {
  padding: 30rpx 30rpx 0 30rpx;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #3d3d3d;
  .flex-box {
    display: flex;
    align-items: center;
    .copy-style {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60rpx;
      height: 40rpx;
      border-radius: 10rpx;
      background: #f3f3f3;
      color: #7c7c7c;
      font-size: 20rpx;
      margin-left: 18rpx;
    }
  }
  .right-box {
    display: flex;
    .img-box {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
      background: #3d3d3d;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 10rpx;
      image {
        width: 40%;
        height: 60%;
        // height: 80%;
      }
    }
  }
}

.whole {
  border-radius: 40rpx 40rpx 0 0;
  padding: 0 36rpx 60rpx 36rpx;
  text-align: center;
  box-sizing: border-box;
  // max-height: 1000rpx;
  // overflow: auto;
  .top-step {
    padding: 0 146rpx;
    position: relative;
    margin-bottom: 64rpx;
  }
  .line {
    position: absolute;
    width: 100rpx;
    height: 4rpx;
    background: #d8d8d8;
  }
  .flex {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .circle {
    background: linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    line-height: 40rpx;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
    position: relative;
    .dec {
      transform: translateX(-45%);
      bottom: -50rpx;
      position: absolute;
      font-size: 28rpx;
      color: #3d3d3d;
      width: max-content;
    }
  }
  .img-code {
    width: 600rpx;
    height: 600rpx;
    border-radius: 20rpx;
    // background:#ccc;
  }
  .img-code-style {
    width: 500rpx;
    height: 400rpx;
    border-radius: 20rpx;
    // background:#ccc;
  }
  .tip {
    font-family: Source Han Sans;
    font-size: 28rpx;
    font-weight: bold;
    margin-top: 10rpx;
    text-align: center;
  }
  .btn-back {
    width: 300rpx;
    height: 100rpx;
    border-radius: 50rpx;
    font-size: 40rpx;
    border: 2px solid #d8d8d8;
    color: #3d3d3d;
  }
  .btn-next {
    width: 300rpx;
    height: 100rpx;
    border-radius: 50rpx;
    font-size: 40rpx;
    color: #fff;
    border: 2px solid linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
    background: linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
  }
  .noact {
    opacity: 0.4;
  }
}
.margin-bottom-style {
  padding-top: 128rpx;
}

.ss-reset-button {
  padding: 0;
  margin: 0;
  font-size: inherit;
  background-color: transparent;
  color: inherit;
  position: relative;
  border: 0rpx;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  text-align: center;
  text-decoration: none;
  white-space: nowrap;
  vertical-align: baseline;
  transform: translate(0, 0);
}
.ss-reset-button.button-hover {
  transform: translate(1px, 1px);
  background: none;
}

.ss-reset-button::after {
  border: none;
}
.btn-next[disabled] {
  background: rgba(115, 121, 136, 0.4) !important;
}
</style>